class CheckInsController < ApplicationController
  before_filter :except => [:index, :create] do |controller|
    controller.authorize_permissions({:blocked_permissions => ["courier"]})
  end

  # GET /check_ins
  # GET /check_ins.json
  def index
    @noItem = "Checkin Items"
    @yesItemPrefix = "Checkin "
    if params[:q]
      @identifier = Identifier.find_by_identifier_value(params[:q])
      if @identifier.nil?
	    flash_msg = "Identifier \"#{params[:q]}\" not found"
        flash.now[:notice] = flash_msg
	    @title = @noItem
      else
        @item = @identifier.item
        @type = @item.item_type
        @item_type = (@type)?(@type.item_type):("No Type")

		generate_container(@item)

        @title = @yesItemPrefix + @item.display_name

		@check_in = CheckIn.new
		
        render 'item'
      end
    else
      @title = @noItem
    end
  end

  # POST /check_ins
  # POST /check_ins.json
  def create
    if request.content_type == "application/json"
      @check_in = CheckIn.create(
        :item => Item.find_by_id(params["item_id"]),
        :location => Location.find_by_id(params["location_id"]),
        # We're actually getting the courier id here
        :user => Courier.find_by_id(params["user_id"]).user,
        :action => "pick_up"
      )
    else
      @check_in = CheckIn.new(params[:check_in])
    end
	
    respond_to do |format|
      if @check_in.save
        flash[:notice] = 'CheckIn was successful.'
        format.html { redirect_to check_ins_path }
        format.json { render :json => @check_in, :status => :created, :location => @check_in }
      else
        flash[:notice] = 'CheckIn was not successful.'
        @item = @check_in.item
        unless @item == nil then
          @title = "Checkin " + @item.display_name
        end
          format.html { render 'item' }
          format.json { render :json => @check_in, :status => :created, :location => @check_in }
      end
    end
  end

  # DELETE /check_ins/1
  # DELETE /check_ins/1.json
  def destroy
    @check_in = CheckIn.find(params[:id])
    @check_in.destroy

    respond_to do |format|
      format.html { redirect_to(check_ins_url) }
      format.json  { head :ok }
    end
  end
end
